package com.dynomedia.esearch.util.groupkeycache;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dynomedia.esearch.util.groupkeycache.KeyBuffer.Key;
import com.dynomedia.esearch.util.groupkeycache.util.ConsumerThreadPool;
import com.dynomedia.esearch.util.groupkeycache.util.GkcConfig;

/***
 * KeyBufferConsumer线程实例将以阻塞式的轮询获得KeyBuffer的缓存数据。
 * @author Administrator
 *
 */
public class KeyBufferConsumer implements Runnable{
	
	private static final Log logger = LogFactory.getLog(KeyBufferConsumer.class);
	
	/** 本地的Bufferkeys容器*/
	private Collection<Key> localBufferkeys = new ArrayList<Key>();
	
	static{
		for(int i=0;i<GkcConfig.getInstance().getKeyBufferConsumerThreadCount();i++){
			ConsumerThreadPool.submit(new KeyBufferConsumer());
		}
		if(logger.isInfoEnabled()) logger.info("KeyBufferConsumer init complete,keyBufferConsumerThreadCount = "+GkcConfig.getInstance().getKeyBufferConsumerThreadCount());		
	}
	
	private KeyBufferConsumer(){}
	
	public static void start(){}
	
	public void run(){
		while(ConsumerThreadPool.isRunning()){
			try{
				localBufferkeys = KeyBuffer.drainTo(localBufferkeys);
				if(localBufferkeys != null){
					if(logger.isDebugEnabled()) logger.debug("KeyBufferConsumer receive localBufferkeys size = "+localBufferkeys.size()+" by Thread:"+Thread.currentThread().getName());
					for(Key key:localBufferkeys){
						GroupkeyCache.add(key.getId(),key.getGroup(),key.getKey());
					}
				}
				localBufferkeys.clear();
			}catch(Exception e){
				logger.error("KeyBufferConsumer run Error!",e);
				continue;
			}
		}
	}

}
